<template>
  <div>
    <ListTab v-model="activeId" :tabs="tabList" :show-header="!showMobilePage" is-table @tabClick="handleTabClick" />
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="sealing-account min-fill-page">
      <DataDisplay
        :data-list="statisticsList"
        class="mb16 mobile-data"
      />
      <template v-if="!showMobilePage">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          style="margin-bottom: 16px;"
          show-search-btn
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus" />
      </template>
      <div v-loading="listLoading" style="min-height: 300px">
        <u-table
          v-if="list.items.length > 0"
          :data="list.items"
          :height="setTableHeight"
          :row-height="rowHeight()"
          :border="true"
          beautify-table
          header-drag-style
          class="fb-table"
          header-cell-class-name="order-data-header-cell"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          fit
          hightlight-current-row
          @sort-change="sortMethod"
        >
          <u-table-column :sortable="activeId === 2?'custom':null" prop="settle_month" align="left" label="月份" min-width="90">
            <template slot-scope="scope">{{ standardFormatMonth(scope.row.month, 'YYYY/MM') }}</template>
          </u-table-column>
          <u-table-column :sortable="activeId === 2?'custom':null" prop="order_total_amount" align="right" label="订单金额(元)" min-width="130">
            <template slot-scope="scope">
              <PriceColumn
                v-if="scope.row.processState !== MONTH_PROCESS_STATE.TO_BE_SUBMIT && (scope.row.sealTotalAmount || scope.row.sealTotalAmount === 0)"
                :real-val="scope.row.sealTotalAmount"
                :price="scope.row.sealTotalAmount / 100" />
              <span v-else class="cell-font-color">--</span>
            </template>
          </u-table-column>
          <u-table-column :sortable="activeId === 2?'custom':null" prop="txn_total_amount" align="right" label="流水金额(元)" min-width="130">
            <template slot-scope="scope">
              <PriceColumn
                v-if="scope.row.processState !== MONTH_PROCESS_STATE.TO_BE_SUBMIT && (scope.row.sealTotalFlow || scope.row.sealTotalFlow === 0)"
                :real-val="scope.row.sealTotalFlow"
                :price="scope.row.sealTotalFlow / 100" />
              <span v-else class="cell-font-color">--</span>
            </template>
          </u-table-column>
          <u-table-column :sortable="activeId === 2?'custom':null" prop="order_payment_total_amount" align="right" label="核销金额(元)" min-width="130">
            <template slot-scope="scope">
              <PriceColumn
                v-if="scope.row.processState !== MONTH_PROCESS_STATE.TO_BE_SUBMIT && (scope.row.sealTotalChargeOff || scope.row.sealTotalChargeOff === 0)"
                :real-val="scope.row.sealTotalChargeOff"
                :price="scope.row.sealTotalChargeOff / 100" />
              <span v-else class="cell-font-color">--</span>
            </template>
          </u-table-column>
          <u-table-column :sortable="activeId === 2?'custom':null" prop="order_cost_item_total_amount" align="right" label="成本金额(元)" min-width="130">
            <template slot-scope="scope">
              <PriceColumn
                v-if="scope.row.processState !== MONTH_PROCESS_STATE.TO_BE_SUBMIT && (scope.row.sealTotalCostAmount || scope.row.sealTotalCostAmount === 0)"
                :real-val="scope.row.sealTotalCostAmount"
                :price="scope.row.sealTotalCostAmount / 100" />
              <span v-else class="cell-font-color">--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="处理状态" min-width="100">
            <template slot-scope="scope">
              <StatusText :color="['#406eff','#fd8546','#31cc9c'][scope.row.processState]" :text="scope.row.processState | setProcessState" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建人" min-width="100">
            <template slot-scope="scope">
              <CheckUserInfo v-if="scope.row.operationName" :label="scope.row.operationName" :user-id="scope.row.operatorId" />
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column :sortable="activeId === 2?'custom':null" prop="seal_date" align="left" label="封账日期" min-width="160">
            <template slot-scope="scope">
              <span v-if="scope.row.sealBillTime">{{ scope.row.sealBillTime | standardFormat('YYYY/MM/DD HH:mm') }}</span>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column :width="operateWidth" align="left" label="操作" min-width="90" fixed="right">
            <template slot-scope="scope">
              <el-button
                v-if="!showMobilePage"
                :disabled="!btnIsOperate(scope)"
                type="text"
                size="small"
                @click="btnOperate(scope)"
              >
                <span v-if="scope.row.processState === 0">提交封账</span>
                <span v-else-if="scope.row.processState === 1">进入封账</span>
                <span v-else-if="scope.row.processState === 2">查看报告</span>
              </el-button>
              <tableOperateBtn v-else>
                <!-- <el-button
                  :disabled="!btnIsOperate(scope)"
                  type="text"
                  size="small"
                  @click="btnOperate(scope)"
                >
                  <span v-if="scope.row.processState === 0">提交封账</span>
                  <span v-else-if="scope.row.processState === 1">进入封账</span>
                  <span v-else-if="scope.row.processState === 2">查看报告</span>
                </el-button> -->
                <el-dropdown-item v-if="scope.row.processState === 0" :disabled="!btnIsOperate(scope)" style="width:90px;text-align: center" @click.native="btnOperate(scope)">
                  <div style="font-size: 14px">提交封账</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.processState === 1" :disabled="!btnIsOperate(scope)" style="width:90px;text-align: center" @click.native="btnOperate(scope)">
                  <div style="font-size: 14px">进入封账</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.processState === 2" :disabled="!btnIsOperate(scope)" style="width:90px;text-align: center" @click.native="btnOperate(scope)">
                  <div style="font-size: 14px">查看报告</div>
                </el-dropdown-item>
              </tableOperateBtn>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else-if="!isInit" style="margin-bottom: 24px" />
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="list.total > 0"
          :current-page.sync="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
        <template v-if="showMobilePage">
          <FilterInput
            ref="FilterToolRef"
            v-model="paramsObj"
            :filter-list="filterList"
            show-search-btn
            show-mobile-icon
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus" />
        </template>
        <template v-else>
          <span style="flex:1;"/>
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </template>
      </fixed-pagination>
    </div>
  </div>
</template>
<script>
import { getList, submitSeal, notSealList, getSealBillStatistics } from '@/api/sealingAccount';
import { getSealBillTab } from '@/api/select';
import { standardFormat, standardFormatMonth } from '@/filters/date';
import { setProcessState } from '@/filters/status';
import { moneyFilter } from '@/filters/number';
import ListTab from '@/components/ListTab';
import { hasRouteAuth } from '@/utils/permission';
import { paramsFormat } from '@/utils/paramsFormat';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import { MessageBox } from 'element-ui';
import DataDisplay from '@/components/Common/baseComponent/dataDisplay';
import paramsDateFormat from '@/mixins/paramsDateFormat';
import TableAdaptive from '@/mixins/tableAdaptive';
import { MONTH_PROCESS_STATE } from '@/utils/const/sealing';
import mobileTable from '@/mixins/mobileTable';
import icon_7 from '@/assets/dataDisplay/icon_7.png';
import icon_17 from '@/assets/dataDisplay/icon_17.png';
import icon_24 from '@/assets/dataDisplay/icon_24.png';
import icon_25 from '@/assets/dataDisplay/icon_25.png';

export default {
  filters: {
    standardFormat,
    setProcessState,
    moneyFilter
  },
  components: {
    ListTab,
    EmptyPlaceholder,
    DataDisplay },
  mixins: [paramsDateFormat, TableAdaptive, mobileTable],
  data() {
    return {
      isInit: true,
      paramsObj: {},
      filterList: [
        { keyword: 'operationName', labelWidth: '70px', name: '创建人', type: 'input' },
        { keyword: 'createTime', labelWidth: '70px', name: '月份', timeType: 'monthrange', type: 'rangeDate', format: 'yyyy/MM' }
      ],
      activeId: -1,
      tabList: [],
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0
      },
      perPage: 20,
      page: 1,
      sortType: '',
      sortName: '',
      listLoading: false,
      statisticsList: [],
      dateDataAttrName: [
        {
          attr: 'createTime',
          start: 'createStart',
          end: 'createEnd',
          endType: 1
        }
      ],
      MONTH_PROCESS_STATE
    };
  },
  computed: {
    tableOutsideHeight() {
      return this.showMobilePage ? 256 : 246;
    }
  },
  created() {
    if (this.$route.query.processState !== undefined) {
      this.activeId = Number(this.$route.query.processState);
    }
    this.fetchData();
    this.getTabList();
  },
  methods: {
    hasRouteAuth,
    standardFormatMonth,
    formatParams(sendPageConfig = true) {
      let params = JSON.parse(JSON.stringify(this.paramsObj));
      // 时间处理
      this.paramsDateFormat(this.dateDataAttrName, params, 's');
      params = paramsFormat(params);
      params.processState = this.activeId;
      params.sortType = this.sortType;
      params.sortName = this.sortName;
      if (sendPageConfig) {
        params.page = this.page;
        params.perPage = this.perPage;
      }
      return params;
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = this.formatParams();
      this.getSealBillData(params);
      this.listLoading = true;
      return getList(this.page, this.perPage, params).then(({ data }) => {
        this.list = data;
        this.isInit = false;
        this.listLoading = false;
      }, result => {
        this.listLoading = false;
      }).catch(e => {
        console.error(e);
      });
    },
    // 排序
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.queryClick(true);
    },
    queryClick() {
      this.fetchData();
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    btnIsOperate(scope) {
      const state = scope.row.processState;
      switch (state) {
        case 0:
          return this.hasRouteAuth('crm:finance:submitSealAmount');
        case 1:
          return this.hasRouteAuth('crm:finance:sellFirstTrial') || this.hasRouteAuth('crm:finance:financeRecheck');
        case 2:
          return this.hasRouteAuth('crm:finance:financeReport');
      }
    },
    btnOperate(scope) {
      if (scope.row.processState === 0) {
        notSealList(scope.row.id).then(res => {
          if (!res.data || !res.data.count) {
            const { sealBillType, dateStart, dateEnd, oldCount } = res.data || {};
            // 当月订单已全部处理，之前月份有可能没有处理完
            this.currentMonthAllClear(scope.row.id, oldCount, { sealBillType, dateStart, dateEnd });
          } else {
            const { sealBillType, dateStart, dateEnd } = res.data;
            // 当月订单没有处理完，之前月份有可能没有处理完
            this.currentMonthNotClear(scope.row.id, res.data, { sealBillType, dateStart, dateEnd });
          }
        }).catch(err => {
          console.error(err);
        });
      } else {
        this.$router.push({
          name: 'sealingStepsDetail',
          params: { id: scope.row.id }
        });
      }
    },
    // 当月订单已全部处理，之前月份有可能没有处理完
    currentMonthAllClear(id, oldCount, query = {}) {
      let msg = '';
      if (oldCount) {
        msg = this.confirmHtmlMsg(`该月之前还有<span style="color: red">${oldCount}</span>个订单未处理，若不处理则不参与本月封账。`, true);
      } else {
        msg = this.confirmHtmlMsg('恭喜该月及之前订单已处理完毕，请确认是否提交封账');
      }
      this.$confirm(msg, '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel',
        center: true,
        dangerouslyUseHTMLString: true,
        type: 'success'
      }).then(() => {
        submitSeal(id).then(res => {
          this.$router.push({
            name: 'sealingStepsDetail',
            params: { id }
          });
        }).catch(err => {
          console.error(err);
        });
      }).catch((e) => {
        console.log('close', e);
        return false;
      });
      if (oldCount) this.bindClickEvent(query);
    },
    // 当月订单没有处理完，之前月份有可能没有处理完
    currentMonthNotClear(id, dataInfo, query = {}) {
      let msg = '';
      if (dataInfo.oldCount && dataInfo.oldCount > 0) {
        msg = this.confirmHtmlMsg(
          `该月还有<span style="color: red">${dataInfo.count}</span>个订单未处理，该月之前还有<span style="color: red">${dataInfo.oldCount}</span>个订单未处理，未处理至待封账订单不参与本次封账。`
          , true
        );
      } else {
        msg = this.confirmHtmlMsg(`该月还有<span style="color: red">${dataInfo.count}</span>个订单需要处理，若不处理则不参与本月封账`, true);
      }
      this.$confirm(msg, '', {
        // confirmButtonText: '去处理',
        confirmButtonText: '继续提交',
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel',
        center: true,
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }).then(() => {
        submitSeal(id).then(res => {
          this.$router.push({
            name: 'sealingStepsDetail',
            params: { id }
          });
        }).catch(err => {
          console.error(err);
        });
        // this.$router.push({
        //   name: 'allOrder',
        //   query
        // });
      }).catch(() => {
        return false;
      });
      this.bindClickEvent(query);
    },
    bindClickEvent(query) {
      const that = this;
      this.$nextTick(() => {
        const eventClick = document.getElementById('eventClick');
        if (eventClick) {
          eventClick.addEventListener('click', function() {
            MessageBox.close();
            that.$router.push({
              name: 'allOrder',
              query: query || {}
            });
          });
        }
      });
    },
    confirmHtmlMsg(msg, callback = false) {
      // <div class="content">1、封账月份必须所有订单状态为待封账</div>
      // <div class="content">2、封账月份前的订单，若状态为待封账，则参与封账；否则不参与本次封账</div>
      return `
        ${msg}${callback ? '<span id="eventClick" style="color:#406EFF;margin-left:5px;cursor:pointer;">去处理>></span>' : ''}
        <div class="diy-tooltip-container">
          <div class="diy-hover">
            <div class="diy-tooltip">
              <div>若订单状态为待封账，则参与封账；否则不参与本次封账</div>
            </div>
            <div class="diy-tooltip-content">封账规则说明 <tipIcon is-diy></tipIcon></div>
          </div>
        </div>
      `;
    },
    handleTabClick(id) {
      this.activeId = id;
      this.queryClick();
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
    },
    async getTabList() {
      try {
        const result = await getSealBillTab();
        if (result.code === 200) {
          this.tabList = result.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 获取统计数据面板
    async getSealBillData(paramsObj = '') {
      try {
        const params = paramsObj || this.formatParams(false);
        const { page, perPage } = params;
        if (page) delete params.page;
        if (perPage) delete params.perPage;
        const res = await getSealBillStatistics(params);
        const { code, data = {}} = res;
        if (code === 200) {
          const { sealOrderAmount, sealFlowAmount, sealChargeAmount, sealCostAmount } = data;
          this.statisticsList = [
            { data: sealOrderAmount / 100, label: '订单金额', icon: icon_7 },
            { data: sealFlowAmount / 100, label: '流水金额', icon: icon_17 },
            { data: sealChargeAmount / 100, label: '核销金额', icon: icon_24 },
            { data: sealCostAmount / 100, label: '成本金额', icon: icon_25 }
          ];
        }
      } catch (error) {
        console.log(error);
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import '@/styles/placeholder.scss';
.sealing-account {
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding: 20px 20px 55px 20px;
}
</style>
<style lang="scss">
.diy-tooltip-container {
  margin-top: 20px;
  position: relative;
  text-align: right;
  .diy-tooltip {
    position: absolute;
    top: -50px;
    right: -23px;
    background: #303133;
    color: #fff;
    border-radius: 4px;
    padding: 10px;
    z-index: 2200;
    font-size: 12px;
    line-height: 1.2;
    min-width: 10px;
    word-wrap: break-word;
    text-align: left;
    max-width: 240px;
    display: none;
    &::after {
      position: absolute;
      content: '';
      display: block;
      width: 0;
      height: 0;
      bottom: -12px;
      left: 68%;
      margin-left: -6px;
      border-top: 6px solid #333;
      border-right: 6px solid transparent;
      border-bottom: 6px solid transparent;
      border-left: 6px solid transparent;
    }
    .content {
      margin-bottom: 5px;
      line-height: 1.2;
      font-weight: normal;
    }
  }
  .diy-tooltip-content {
    display: inline-block;
    cursor: pointer;
    color:#999;
    font-weight:normal;
    font-size:13px;
    text-align: right;
  }
  .diy-hover {
    display: inline-block;
    &:hover {
      .diy-tooltip {
        display: block;
      }
    }
  }
}
</style>
<style lang="scss">
.mobile-table {
  & td {
    height: 40px !important;
  }
}
</style>
